package com.mwy.springbootrabbitmq.mq.direct.receive;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * 路由队列--消费者01
 */
public class Receive01 {

    //声明交换机
    private final static String EXCHANGE_NAME = "exchange_direct";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/mwy");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"direct");
        //声明队列
        String queueName = channel.queueDeclare().getQueue();
        //将队列和交换机绑定(可以绑定多个)
        channel.queueBind(queueName,EXCHANGE_NAME,"black");
        channel.queueBind(queueName,EXCHANGE_NAME,"orange");
        //消费回调函数
        DeliverCallback deliverCallback = (consumerTag,delivery)->{
            String message = new String(delivery.getBody(),"UTF-8");
            System.out.println("消费者01，接到消息"+message);
        };
        //消费消息
        channel.basicConsume(queueName,true,deliverCallback,consumerTag->{});
    }
}
